package com.refusea.commons.utils

import java.net.URLEncoder
import java.nio.charset.StandardCharsets

/**
 * @author Zhang Yan
 * @date 2023-5-18
 **/
object Strings {

    private const val COMMA = ','

    private const val EMPTY: String = ""

    /**
     * 用分隔符将字符串分割成只读 list, **注意**: 返回的 list 不会包含空字符串
     *
     * @param str           要分割的字符串
     * @param separatorChar 分隔符
     * @return 列表, 如果字符串为空会返回空列表
     */
    @JvmStatic
    fun split(str: String?, separatorChar: Char): List<String> {

        if (str == null) {
            return emptyList()
        }

        val len: Int = str.length
        if (len == 0) {
            return emptyList()
        }

        val list = mutableListOf<String>()
        var i = 0
        var start = 0
        var match = false
        while (i < len) {
            if (str[i] == separatorChar) {
                if (match) {
                    list.add(str.substring(start, i))
                    match = false
                }
                start = ++i
                continue
            }
            match = true
            i++
        }
        if (match) {
            list.add(str.substring(start, i))
        }

        return list.toList()
    }

    /** same as `split(String, ',');`  */
    @JvmStatic
    fun split(str: String?): List<String> {
        return split(str, COMMA)
    }

    @JvmStatic
    fun safeurl(url: String?): String {
        return if (url == null) {
            EMPTY
        } else {
            URLEncoder.encode(url, StandardCharsets.UTF_8)
        }
    }


}
